package com.cq.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * 列表值约束验证器
 *
 * @author 程崎
 * @since 2022/09/20
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private static final Set<Integer> SET = new HashSet<>();

    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] values = constraintAnnotation.value();
        for (int value : values) {
            SET.add(value);
        }
    }

    /**
     * 是否有效
     *
     * @param value   需要校验的值
     * @param context 上下文
     * @return boolean
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return SET.contains(value) || value == null;
    }
}
